package com.unis.XmlNetty;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.dom4j.Document;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

import com.unis.XmlNetty.beans.XmlPackge;
import com.unis.XmlNetty.beans.loaclConfig;


public class byteToXmlServerHandle extends SimpleChannelHandler {
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		// TODO Auto-generated method stub	
		Channel newChannel = e.getChannel();
		System.out.println("new connection "+newChannel.getRemoteAddress().toString());
		byteToXmlServer.allChannel.add(e.getChannel());
		byteToXmlServer.getClient();
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		// TODO Auto-generated method stub
		if(e.getMessage() instanceof XmlPackge){
			XmlPackge xmlpackge = (XmlPackge)e.getMessage();
			String filename = xmlpackge.getJdxh();		
			Document document = XmlUtil.ConfigToXml(xmlpackge.getJdxh());			
			e.getChannel().write(new XmlPackge(filename, document));
			System.out.println("["+sdf.format(new Date())+"]发送节点序号为:"+xmlpackge.getJdxh()+"的配置文件至客户端");
		}else if(e.getMessage() instanceof loaclConfig){
			loaclConfig config = (loaclConfig)e.getMessage();
			ConfigService.insertOrUpdate(config);
			if("1".equals(config.getC_CSLX())){
				System.out.println("["+sdf.format(new Date())+"]更新节点序号为:"+config.getC_BDJD()+"的发送进度信息");
			}else{
				System.out.println("["+sdf.format(new Date())+"]更新节点序号为:"+config.getC_BDJD()+"的接收进度信息");
			}
		}
	}

	
	@Override
	public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		// TODO Auto-generated method stub
		Channel closedChannel = e.getChannel();
		closedChannel.close();
		System.out.println("connection closed"+closedChannel.getRemoteAddress().toString());
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
		// TODO Auto-generated method stub
		e.getCause().printStackTrace();
		Channel exceptionChannel = e.getChannel();
		exceptionChannel.close();
	}
}
